<template>
	<view v-if="tags" class="ts-tag-selector-row">
		<block v-for="(tag, index) in tags" :key="index">
			<view class="ts-tag-selector-tag">
				<ts-tag :text="tag" :size="size" :circle="circle" :type="type" :inverted="!(selected[index])" @click="setInverted(index)"></ts-tag>
			</view>
		</block>
	</view>
</template>

<script>
	export default {
		name: 'ts-tag-selector',
		props: {
			defaultIndex: {
				type: [Array, Number],
				default () {
					return 0;
				},
			},
			tags: {
				type: Array,
				default () {
					return [];
				},
			},
			multiple: { //允许多选
				type: [String, Boolean],
				default: false,
			},
			type: { //标签类型default、primary、success、warning、danger、royal
				type: String,
				default: 'default'
			},
			size: { //标签大小 normal, small
				type: String,
				default: 'normal'
			},
			circle: { //是否为圆角
				type: [String, Boolean],
				defalut: false
			}
		},
		data() {
			return {
				//selectedIndex_: [],
				selected: [],
			}
		},
		watch: {
			defaultIndex(val) {
				//外部通过程序设置属性的值
				this.reset(val);
				//this.selectedIndex_ = val;
			}
		},
		onLoad() {
			this.selected = [];
			for (let i = 0; i < this.tags.length; i++) {
				this.selected.push(false);
			}

			this.reset(this.defaultIndex);
		},
		methods: {
			reset(val) {

				console.log('reset options');

				//全部清除选中状态
				for (let i = 0; i < this.tags.length; i++) {
					if (this.selected[i] === true) {
						this.$set(this.selected, i, false);
					}
				}
				//设置默认值
				if (Array.isArray(val)) {
					for (let i = 0; i < val.length; i++) {
						let idx = val[i];
						this.$set(this.selected, idx, true)
					}
				} else {
					this.$set(this.selected, val, true)
				}
			},

			setInverted(index) {
				const v = !this.selected[index];
				if (this.multiple) {
					this.$set(this.selected, index, v); //

					let selectedIndex = [];
					for (let i = 0; i < this.selected.length; i++) {
						if (this.selected[i]) {
							selectedIndex.push(i);
						}
					}

					//this.selectedIndex_ = selectedIndex;
					this.$emit('change', {
						tags: this.tags,
						selected: this.selected,
						selectedIndex: selectedIndex,
					})

				} else {
					//不允许多选，清除所有选项，只设置一个值
					if (this.selected[index] === false) {
						for (let i = 0; i < this.tags.length; i++) {
							if (this.selected[i] === true) {
								this.$set(this.selected, i, false);
							}
						}
						this.$set(this.selected, index, v);
					} else {
						return; //没有改变，不触发事件
					}

					//this.selectedIndex_ = index;
					this.$emit('change', {
						tags: this.tags,
						selected: this.selected,
						selectedIndex: index,
					})
				}

			},
		}
	}
</script>


<style>
	.ts-tag-selector-row {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
	}

	.ts-tag-selector-tag {
		display: flex;
		flex-direction: row;
		padding-top: 10upx;
		padding-right: 10upx;
	}
</style>
